import { createRouter, createWebHashHistory } from 'vue-router'
import { notFoundAndNoPower, staticRoutes } from '@/router/route'
import LocalStorage from '@/utils/LocalStorage'
import { NextLoading } from '@/utils/loading'
import { useAppsStore } from '@/stores/modules/app'
import { useTabsStore } from '@/stores/modules/tabs'
import { storeToRefs } from 'pinia'
import type { lockState } from '@/types/tabs'

export const router = createRouter({
  history: createWebHashHistory(),
  /**
   * 说明：
   * 1、notFoundAndNoPower 默认添加 404、401 界面，防止一直提示 No match found for location with path 'xxx'
   * 2、backEnd.ts(后端控制路由)、frontEnd.ts(前端控制路由) 中也需要加 notFoundAndNoPower 404、401 界面。
   *    防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
   */
  routes: [...staticRoutes, ...notFoundAndNoPower]
})

const getFirstPath = (info: any) => {
  let path = info.path
  if (info?.children && info.children.length > 0) {
    const childerPath = getFirstPath(info.children[0])
    if (childerPath.startsWith('/')) {
      path = childerPath
    } else {
      path += childerPath
    }
  }
  return path
}

export const authLogin = async (token?: string, isLoading = true) => {
  try {
    if (!token) {
      token = LocalStorage.get(import.meta.env.VITE_TOKEN_LOACTION_NAME)
    }
    if (token) {
      if (isLoading) NextLoading.start()
      const userStore = useAppsStore()
      const { setToken } = userStore
      await setToken(token)
      const tabStore = useTabsStore()
      const { getRouter } = tabStore
      await getRouter()
      if (isLoading) {
        setTimeout(() => {
          NextLoading.done()
        }, 100)
      }
      const info: any = router.getRoutes().find((el: any) => el.path === '/')
      return getFirstPath(info || router.getRoutes()[0])
    } else {
      return false
    }
  } catch (e) {
    console.log('错误', e)
    setTimeout(() => {
      NextLoading.done()
    }, 100)
    return false
  }
}

router.beforeEach(async (to: any, from, next) => {
  const tabStore = useTabsStore()
  const userStore = useAppsStore()
  const { addVisitedRoute, unlock, getLeaverOne } = tabStore
  const { getLoginStatus: loginStatus } = storeToRefs(userStore)
  const { getLocaks: locks, getCurrenName: currenName } = storeToRefs(tabStore)
  //  未登录自动登录
  if (!loginStatus.value && to.name !== 'Login') {
    const firthPath = await authLogin()
    if (!to.meta.noLogin) {
      if (!firthPath) next('/login')
      if (to.path === '/') {
        return next(firthPath)
      }
      return next({
        path: to.path,
        query: to.query
      })
    }
  }
  //  已登录状态前往登录页重定向到首页
  if (to.name === 'Login' && loginStatus.value) {
    const info: any = router.getRoutes().find((el: any) => el.path === '/')
    return next(info.children[0].path)
  }
  // 自动添加路由缓存
  await addVisitedRoute(from, to)
  // 解锁缓存组
  if (locks.value.length > 0) {
    const lockIndex = locks.value.findIndex((el: lockState) => {
      return el.childer.some((item: any) => item.name === to.name)
    })
    if (lockIndex >= 0) {
      const lockInfo: lockState = locks.value[lockIndex]
      const name = lockInfo.childer.at(-1).name
      if (name !== to.name) {
        return next({ name })
      }
      unlock(lockIndex)
    }
  }
  //  详情页被清楚父级路由缓存,找不到选中菜单,跳转到首页
  if (to.meta.isPage && !currenName.value) {
    const info: any = router.getRoutes().find((el: any) => el.path === '/')
    return next(getFirstPath(info || router.getRoutes()[0]))
  }
  // 获取一级菜单下标
  getLeaverOne(to)
  //  放行路由
  next()
})

export default router
